import React, { useEffect, useState } from 'react';
import { Modal, Descriptions, Avatar, Tag, Tabs, Table, Progress, Timeline, Button, Space } from 'antd';
import { UserOutlined, TrophyOutlined, BookOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { getUserLearningProgress, getUserAchievements, getUserOperationLogs, getUserLoginHistory } from '@/services/userManagementApi';
import moment from 'moment';

interface UserDetailProps {
  visible: boolean;
  user?: USER.UserModel;
  onCancel: () => void;
}

const UserDetail: React.FC<UserDetailProps> = ({ visible, user, onCancel }) => {
  const [loading, setLoading] = useState(false);
  const [learningProgress, setLearningProgress] = useState<any[]>([]);
  const [achievements, setAchievements] = useState<any[]>([]);
  const [operationLogs, setOperationLogs] = useState<any[]>([]);
  const [loginHistory, setLoginHistory] = useState<any[]>([]);

  useEffect(() => {
    if (visible && user) {
      loadUserData();
    }
  }, [visible, user]);

  const loadUserData = async () => {
    if (!user) return;
    
    setLoading(true);
    try {
      const [progressRes, achievementsRes, logsRes, loginRes] = await Promise.all([
        getUserLearningProgress(user.id),
        getUserAchievements(user.id),
        getUserOperationLogs(user.id, { limit: 10 }),
        getUserLoginHistory(user.id, { limit: 10 }),
      ]);

      setLearningProgress(progressRes.data || []);
      setAchievements(achievementsRes.data || []);
      setOperationLogs(logsRes.data?.list || []);
      setLoginHistory(loginRes.data?.list || []);
    } catch (error) {
      console.error('加载用户数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (!user) return null;

  // 状态标签颜色映射
  const statusColorMap = {
    active: 'green',
    inactive: 'orange',
    banned: 'red',
  };

  // 角色标签颜色映射
  const roleColorMap = {
    admin: 'red',
    user: 'default',
  };

  // 学习进度表格列
  const progressColumns = [
    {
      title: '课程名称',
      dataIndex: 'course_title',
      key: 'course_title',
    },
    {
      title: '进度',
      dataIndex: 'progress_percentage',
      key: 'progress_percentage',
      render: (progress: number) => (
        <Progress percent={progress} size="small" />
      ),
    },
    {
      title: '完成课时',
      key: 'lessons',
      render: (record: any) => `${record.completed_lessons}/${record.total_lessons}`,
    },
    {
      title: '最后学习',
      dataIndex: 'last_accessed_at',
      key: 'last_accessed_at',
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm'),
    },
  ];

  // 操作日志表格列
  const logColumns = [
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  // 登录历史表格列
  const loginColumns = [
    {
      title: 'IP地址',
      dataIndex: 'ip_address',
      key: 'ip_address',
    },
    {
      title: '设备信息',
      dataIndex: 'user_agent',
      key: 'user_agent',
      ellipsis: true,
    },
    {
      title: '登录时间',
      dataIndex: 'login_time',
      key: 'login_time',
      render: (time: string) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <Descriptions column={2} bordered>
          <Descriptions.Item label="用户ID">{user.id}</Descriptions.Item>
          <Descriptions.Item label="用户名">{user.username}</Descriptions.Item>
          <Descriptions.Item label="昵称">{user.nickname}</Descriptions.Item>
          <Descriptions.Item label="邮箱">{user.email}</Descriptions.Item>
          <Descriptions.Item label="手机号">{user.phone || '-'}</Descriptions.Item>
          <Descriptions.Item label="性别">
            {user.gender === 'male' ? '男' : user.gender === 'female' ? '女' : '其他'}
          </Descriptions.Item>
          <Descriptions.Item label="出生日期">
            {user.birth_date ? moment(user.birth_date).format('YYYY-MM-DD') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="角色">
            <Tag color={roleColorMap[user.role as keyof typeof roleColorMap] || 'default'}>
              {user.role === 'admin' ? '管理员' : '用户'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="状态">
            <Tag color={statusColorMap[user.status]}>
              {user.status === 'active' ? '正常' : user.status === 'inactive' ? '未激活' : '已封禁'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="等级">{user.level}</Descriptions.Item>
          <Descriptions.Item label="经验值">{user.experience?.toLocaleString()}</Descriptions.Item>
          <Descriptions.Item label="积分">{user.points?.toLocaleString()}</Descriptions.Item>
          <Descriptions.Item label="学习时长">
            {Math.round((user.total_study_time || 0) / 60)} 小时
          </Descriptions.Item>
          <Descriptions.Item label="练习次数">{user.practice_count?.toLocaleString()}</Descriptions.Item>
          <Descriptions.Item label="最后登录">
            {user.last_login_at ? moment(user.last_login_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="注册时间">
            {moment(user.created_at).format('YYYY-MM-DD HH:mm:ss')}
          </Descriptions.Item>
        </Descriptions>
      ),
    },
    {
      key: 'learning',
      label: '学习进度',
      children: (
        <Table
          columns={progressColumns}
          dataSource={learningProgress}
          rowKey="course_id"
          pagination={false}
          loading={loading}
          size="small"
        />
      ),
    },
    {
      key: 'achievements',
      label: '成就列表',
      children: (
        <div style={{ maxHeight: 400, overflow: 'auto' }}>
          {achievements.length > 0 ? (
            <Timeline>
              {achievements.map((achievement, index) => (
                <Timeline.Item
                  key={index}
                  dot={<TrophyOutlined style={{ color: '#faad14' }} />}
                >
                  <div>
                    <strong>{achievement.name}</strong>
                    <div style={{ color: '#666', fontSize: '12px' }}>
                      {achievement.description}
                    </div>
                    <div style={{ color: '#999', fontSize: '12px' }}>
                      获得时间: {moment(achievement.unlocked_at).format('YYYY-MM-DD HH:mm')}
                    </div>
                  </div>
                </Timeline.Item>
              ))}
            </Timeline>
          ) : (
            <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
              暂无成就记录
            </div>
          )}
        </div>
      ),
    },
    {
      key: 'logs',
      label: '操作日志',
      children: (
        <Table
          columns={logColumns}
          dataSource={operationLogs}
          rowKey="id"
          pagination={false}
          loading={loading}
          size="small"
        />
      ),
    },
    {
      key: 'login',
      label: '登录历史',
      children: (
        <Table
          columns={loginColumns}
          dataSource={loginHistory}
          rowKey="id"
          pagination={false}
          loading={loading}
          size="small"
        />
      ),
    },
  ];

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Avatar
            size={40}
            src={user.avatar}
            icon={<UserOutlined />}
          />
          <div>
            <div>{user.nickname}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>@{user.username}</div>
          </div>
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
      ]}
      width={800}
      destroyOnClose
    >
      <Tabs items={tabItems} />
    </Modal>
  );
};

export default UserDetail;
